/*
 * @Description: 路由定义
 * @Autor: lcz
 * @LastEditors: lcz
 * @LastEditTime: 2023-10-08 13:38:51
 */
import { Suspense, useEffect } from "react";
import { BrowserRouter, Route, Routes, RouteProps, Navigate, useNavigate } from "react-router-dom";
// BrowserRouter HashRouter
import routes from "./config";
import styles from "./index.module.scss";
import { Spin } from "antd";

const Redirect = ({ to }: { to: string }) => {
  let navigate = useNavigate();
  useEffect(() => {
    navigate(to);
  });
  return null;
};

const RoutesConfig = () => {
  /* 懒加载加载动画、未渲染完成时候 */
  const RouteElementLoading = (route: RouteProps): React.ReactNode => {
    if (!route.element) return null;
    return (
      <Suspense
        fallback={
          <div className={styles.loadingBox}>
            <Spin size='large'></Spin>
          </div>
        }
      >
        {/* @ts-ignore */}
        <route.element />
      </Suspense>
    );
  };

  /* 路由多层级渲染 */
  function depRouteRegist(routes: RouteProps[]) {
    return routes.map(route => (
      <Route key={route.path} path={route.path} element={RouteElementLoading(route)}>
        {route.children && depRouteRegist(route.children as RouteProps[])}
      </Route>
    ));
  }

  return (
    <BrowserRouter>
      <Routes>
        <Route path='/' element={<Redirect to='/home' />} />
        {/* @ts-ignore */}
        {depRouteRegist(routes)}
        <Route key='*' path='*' element={<Navigate to='/404' />} />
      </Routes>
    </BrowserRouter>
  );
};

export default RoutesConfig;
